<template>
  <el-dialog :visible.sync="dialogShow" :before-close="check" title="编辑/查看">
    <el-form ref="scopeData" :model="scopeData" :rules="scopeRules" label-position="left">
      <el-form-item class="dialog-title" label="用户名ID" label-width="80px" prop="userId">
        <el-row>
          <el-col :span="24">
            <el-input v-model.trim="scopeData.userId" style="width:190px;float:left" size="medium" placeholder="请输入用户名id" />
            <div class="notice">允许输入字母、数字或字母与数字的组合，不超过20个字符</div>
          </el-col>
          <!-- <el-col :span="10">
            <div class="notice">允许输入字母、数字或字母与数字的组合，不超过20个字符</div>
          </el-col> -->
        </el-row>
      </el-form-item>
      <el-form-item label="昵称" label-width="80px" prop="userName">
        <el-row>
          <el-col :span="7">
            <el-input v-model.trim="scopeData.userName" style="width:190px;float:left" size="medium" placeholder="请输入昵称" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="密码" label-width="80px" prop="passWord">
        <el-row>
          <el-col :span="24">
            <el-input v-model.trim="scopeData.passWord" style="width:190px;float:left" type="password" size="medium" placeholder="请输入密码" />
            <div class="notice">允许输入字母、数字或字母与数字的组合，不超过20个字符</div>
          </el-col>
          <!-- <el-col :span="17">
            <div class="notice">允许输入字母、数字或字母与数字的组合，不超过20个字符</div>
          </el-col> -->
        </el-row>
      </el-form-item>
      <el-form-item class="is-required" label="重复密码" label-width="80px">
        <el-row>
          <el-col :span="7">
            <el-input v-model.trim="secondPassword" style="width:190px" type="password" size="medium" placeholder="请再次输入密码" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-row>
        <el-col :span="10">
          <el-form-item label="状态" label-width="80px" prop="status">
            <el-select v-model="scopeData.status" style="width:190px" size="medium" placeholder="请选择">
              <el-option value="0" label="生效" />
              <el-option value="1" label="失效" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10" class="margin-left">
          <el-form-item class="is-required" label="角色" label-width="80px" prop="defaultRole">
            <el-select v-model="defaultRole" style="width:190px" size="medium" placeholder="请选择">
              <el-option v-for="role in scopeData.roleList" :key="role.id" :value="role.id" :label="role.name" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="邮箱" label-width="80px" prop="mail">
            <el-input v-model.trim="scopeData.mail" style="width:190px" size="medium" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="9" class="margin-left">
          <el-form-item label="手机号" label-width="80px" prop="phoneNumber">
            <el-input v-model="scopeData.phoneNumber" style="width:190px" size="medium" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="15">
          <el-form-item label="备注" label-width="80px" prop="remark">
            <el-input v-model="scopeData.remark" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <div class="btnList">
          <el-button
            style="width:41%"
            type="primary"
            @click="saveUser"
          >保存</el-button>
          <el-button
            type="primary"
            plain
            style="width:41%"
            class="marginBtn"
            @click="check"
          >取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { checkMail, checkPhone, numAndWord } from '@/utils/validate'
import secret from '@/utils/secret'
import { editUser, saveEdit, addUser, saveAdd } from '@/api/userManage'
import { mapGetters } from 'vuex'
export default {
  name: 'EditUser',
  props: {
    // 遮罩
    dialogTableVisible: {
      type: Boolean,
      default: false
    },
    // 用户属性_编辑时
    scope: {
      type: Object,
      default: null
    },
    // 用户新增角色时
    addScope: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 校验邮箱是否合法
    const checkMailData = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!checkMail(value)) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    // 校验手机号是否合法
    const checkPhoneNumber = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!checkPhone(value)) {
        callback(new Error('手机格式不正确'))
      } else {
        callback()
      }
    }
    // 校验用户名是否合法
    const checkUserName = (rule, value, callback) => {
      if (!numAndWord(value) || !value) {
        callback(new Error('仅允许输入数字和字母'))
      } else {
        callback()
      }
    }
    return {
      loadings: true,
      dialogShow: false, // 遮罩
      secondPassword: null, // 再次密码
      oldUserId: '',
      scopeData: {
        userId: null, // id
        userName: null, // 名字
        passWord: null, // 密码
        status: null, // 状态
        phoneNumber: null, // 手机号
        mail: null, // 邮箱
        remark: null, // 备注
        roleList: null,
        id: null // 主键id
      },
      defaultRole: null, // 默认角色
      scopeRules: {
        userId: [{
          required: true,
          trigger: 'blur',
          validator: checkUserName
        }, {
          min: 1,
          max: 20,
          message: '长度在 1 到 20 个字符',
          trigger: 'blur'
        }],
        userName: [{
          required: true,
          message: '请输入昵称',
          trigger: 'blur'
        }, {
          min: 1,
          max: 20,
          message: '长度在 1 到 20 个字符',
          trigger: 'blur'
        }],
        passWord: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }, {
          min: 1,
          max: 20,
          message: '长度在 1 到 20 个字符',
          trigger: 'blur'
        }],
        // secondPassword: [{
        //   required: true,
        //   trigger: 'blur',
        //   validator: checkSecondPassword
        // }],
        mail: [{
          required: false,
          trigger: 'blur',
          validator: checkMailData
        }],
        phoneNumber: [{
          required: false,
          trigger: 'blur',
          validator: checkPhoneNumber
        }],
        remark: [{
          required: false,
          trigger: 'blur',
          message: '请输入备注'
        }, {
          min: 1,
          max: 20,
          message: '长度在 1 到 20 个字符',
          trigger: 'blur'
        }],
        status: [{
          required: true,
          trigger: 'blur',
          message: '请选择状态'
        }]
      }
    }
  },
  computed: {
    ...mapGetters(['assignment', 'token'])
  },
  watch: {
    // 遮罩监听
    dialogTableVisible(newVal) {
      this.dialogShow = newVal
    },
    // 编辑角色信息
    scope(newVal) {
      var id = newVal.userId
      // 每次点击变化时，通过监听来获取最新值
      this.getList(id)
    },
    // 增加角色信息
    addScope(newVal) {
      // console.log(newVal)
      this.getAdd()
    }
  },
  mounted() {

  },
  methods: {
    // 给父组件传值
    check() {
      this.$emit('closeDialog')
      this.dialogShow = false
    },
    // 请求数据
    getList(id) {
      const data = {
        // token: this.token,
        userId: id
      }
      console.log('请求参数')
      console.log(data)
      editUser(secret.Encrypt(data)).then(response => {
        console.log('返回数据')
        console.log(response)
        var data = response.data
        this.oldUserId = data.userId
        this.scopeData = data
        this.secondPassword = data.passWord
        var userSelect = this.scopeData.roleId
        var defaultRole = this.scopeData.roleList.filter(function(item) {
          return item.id === userSelect
        })
        console.log(this.scopeData.roleList)
        this.defaultRole = defaultRole[0].id
      })
    },
    checkSame(e) {
      if (this.scopeData.passWord !== e) {
        this.$alert('两次密码输入不一致，请重新输入！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.secondPassword = null
          }
        })
      }
    },
    // 新增
    getAdd() {
      const data = {
        // token: this.token
      }
      addUser(secret.Encrypt(data)).then((response) => {
        console.log('返回数据')
        console.log(response)
        this.$refs.scopeData.resetFields()
        // var data = response.data
        this.secondPassword = null
        this.defaultRole = null
        this.scopeData.roleList = response.data.roleList
      })
    },
    // 保存提交
    saveUser() {
      if (this.scopeData.passWord !== this.secondPassword) {
        this.$alert('两次密码输入不一致，请重新输入！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.secondPassword = null
          }
        })
        return
      }
      if (this.defaultRole === null) {
        this.$alert('请选择关联角色', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }
      this.$refs.scopeData.validate(valid => {
        if (valid) {
          this.scopeData.phoneNumber = !this.scopeData.phoneNumber ? '' : this.scopeData.phoneNumber
          this.scopeData.mail = !this.scopeData.mail ? '' : this.scopeData.mail
          this.scopeData.remark = !this.scopeData.remark ? '' : this.scopeData.remark
          var data = {
            // token: this.token,
            id: this.scopeData.id,
            userId: this.scopeData.userId,
            userName: this.scopeData.userName,
            password: this.scopeData.passWord,
            status: this.scopeData.status,
            phoneNumber: this.scopeData.phoneNumber,
            mail: this.scopeData.mail,
            roleId: this.defaultRole,
            remark: this.scopeData.remark
          }
          console.log('请求参数')
          console.log(data)
          // 编辑提交
          if (this.addScope === false) {
            data.oldUserId = this.oldUserId
            // console.log(data)
            saveEdit(secret.Encrypt(data)).then(response => {
              console.log('返回数据')
              console.log(response)
              if (response.resultCode !== '0000') {
                this.$message({
                  message: response.resultDesc,
                  type: 'error'
                })
              } else {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.check()
              }
            })
          } else {
            // 新增提交
            const userCheck = {
              // token: this.token,
              userId: this.scopeData.userId
            }
            console.log('请求参数')
            console.log(userCheck)
            saveAdd(secret.Encrypt(data)).then((response) => {
              if (response.resultCode !== '0000') {
                this.$message({
                  message: response.resultDesc,
                  type: 'error'
                })
              } else {
                console.log('返回结果')
                console.log(response)
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.check()
              }
            })
          }
        }
      })
    }
  }
}
</script>
<style>
  .margin-left{
    /*position: absolute;
    right: 10%;*/
    margin-left: 20px;
  }
</style>
<style scoped>
  .notice{
    font-size: 12px;
    color: red;
    padding-left: 10px;
    float: left;
  }
    .checkbox-per{
    margin-top: -10px;
    padding-left: 60px;
  }
  .dialog-title{
    padding-bottom: -10px;
  }
  .btnList{
    width: 200px;
    text-align: center;
    margin: 0 auto;
  }
  .btn{
    margin-bottom: -20px !important;
    padding-bottom: 10px;
  }
  .marginBtn{
    margin-left: 30px;
  }
  .leftPosition{
    margin-left: 20px;
  }
</style>
